import json

# json文件示例形式
test_json = """
    {
        "name": "BeJson",
        "url": "http://www.bejson.com",
        "page": 88,
        "isNonProfit": true,
        "listNoObject":[1,3,3,3,5],
        "testNull":null,
        "address": {
            "street": "科技园路.",
            "city": "江苏苏州",
            "country": "中国",
            "house": {
                "float":1.0,
                "id":2,
                "men":
                    {
                        "men1":2,
                        "men2":1
                    }
                }
        },
        "links": [
            {
                "name": "Google",
                "url": "http://www.google.com"
            },
            {
                "name": "Baidu",
                "url": "http://www.baidu.com"
            },
            {
                "name": "SoSo",
                "url": "http://www.SoSo.com"
            }
        ],
        "hashtest":28
    }
"""
JsonName = "Circle"
with open(JsonName + ".json", 'rb') as load_f:
    date_json = json.load(load_f)
# date_json = json.loads(test_json)

print(date_json)
print("*" * 10)
# 发送时，每次需要注册新的手机号码，就需要json每次提示mobileTel的value进行发送
# 遍历json文件所有的key对应的value
dic = {}
dicList = []


def pythonType2QtType(arg):
    if isinstance(arg, int):
        return "int"
    elif isinstance(arg, float):
        return "double"
    elif isinstance(arg, str):
        return "QString"
    elif isinstance(arg, bool):
        return "bool"
    elif arg is None:
        return "QString"  # 理论上不允许出现json中带null
    else:
        return "QString"


def dict2list(dic_json, fkey=""):
    if isinstance(dic_json, dict):  # 判断是否是字典类型isinstance 返回True false
        for key in dic_json:
            if isinstance(dic_json[key], dict):  # 如果dic_json[key]依旧是字典类型
                tmp = {"name": str(key), "realtype": "object", "type": str(key), "fkey": str(fkey)}
                dicList.append(tmp)
                dict2list(dic_json[key], key)

            elif isinstance(dic_json[key], list):
                for keyList in dic_json[key]:
                    if isinstance(keyList, dict):
                        dict2list(keyList, str(key))
                        tmp = {"name": str(key), "realtype": "list", "type": "QList<" + str(key) + ">",
                               "fkey": str(fkey)}
                        dicList.append(tmp)
                    else:
                        tmp = {"name": str(key), "isSubTypeNoObject": pythonType2QtType(keyList),
                               "realtype": "list", "type": "QList<" + pythonType2QtType(keyList) + ">",
                               "fkey": str(fkey)}
                        dicList.append(tmp)
                    break
            else:
                tmp = {"name": str(key), "realtype": pythonType2QtType(dic_json[key]),
                       "type": pythonType2QtType(dic_json[key]), "fkey": str(fkey), "defaultValue": dic_json[key]}
                dicList.append(tmp)


dict2list(date_json, JsonName)

print("dicList ---: " + str(dicList))


def deldic(rootJson):
    classList = []
    hashmap = {"JsonName": JsonName, "objects": []}
    for classJson in rootJson:
        if classJson.get('fkey') in classList:
            continue
        else:
            classList.append(classJson.get('fkey'))

    for className in classList:
        tmp = {'name': className, 'methods': []}
        for classJson in rootJson:
            if classJson.get('fkey') == className:
                isSubTypeNoObject = ''
                if 'isSubTypeNoObject' in classJson:
                    isSubTypeNoObject = classJson.get('isSubTypeNoObject')
                if 'defaultValue' in classJson:
                    tmp['methods'].append({"name": classJson.get('name'), "type": classJson.get('type'),
                                           "defaultValue": classJson.get('defaultValue'),
                                           "isSubTypeNoObject": isSubTypeNoObject,
                                           "realtype": classJson.get('realtype')})
                else:
                    tmp['methods'].append({"name": classJson.get('name'), "type": classJson.get('type'),
                                           "defaultValue": '',
                                           "isSubTypeNoObject": isSubTypeNoObject,
                                           "realtype": classJson.get('realtype')})
        hashmap['objects'].append(tmp)
    print("classList ---: " + str(classList))
    print("hashmap ---: " + str(hashmap))

    return hashmap


model = deldic(dicList)

import jinja2

sx = model['objects']
sx = sx[::-1]
model['objects'] = sx
env = jinja2.Environment(loader=jinja2.FileSystemLoader(''))
# print(env.get_template('model_cpp.tmpl').render(model))
output = open(JsonName + ".h", 'w', encoding='utf-8')
output.write(env.get_template('model_h.tmpl').render(model))
output.close()

output = open(JsonName + ".cpp", 'w', encoding='utf-8')
output.write(env.get_template('model_cpp.tmpl').render(model))
output.close()
exit(0)
